package org.brakepedal.server.support.controller.responseBodyAdvice;

import lombok.extern.slf4j.Slf4j;
import org.brakepedal.server.support.http.AbsResponseBody;
import org.brakepedal.server.support.http.ResponseBodyCode;
import org.jetbrains.annotations.NotNull;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * Date: 2023/2/10 21:32
*/
@Slf4j
@RestControllerAdvice(basePackages = "com.pdl.chatroomjava.controller")
public class SetResponseCodeAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(@NotNull MethodParameter returnType, @NotNull Class<? extends HttpMessageConverter<?>> converterType) {
//        log.info("{} -> {}" , Objects.requireNonNull(returnType.getMethod()).getReturnType().getSimpleName(),converterType.getSimpleName());
        // 如果与 setTotalByPageDataAdvice的处理类型相同,则这个advice也处理
        log.info("setCode returnType: {}",returnType);
        return AdviceSupportUtil.isResponseBody(returnType,converterType);
    }

    @Override
    public Object beforeBodyWrite(Object body, @NotNull MethodParameter returnType,
                                  @NotNull MediaType selectedContentType,
                                  @NotNull Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  @NotNull ServerHttpRequest request, @NotNull ServerHttpResponse response) {
        /*
        * 如果不是json,则直接返回 body, 该逻辑在所有的controllerAdvice里都有,所以抽离出来,
        * 该逻辑已移入 HandleNotJsonTypeAspect 切面
        * */


        ResponseBodyCode code = ((AbsResponseBody) body).getCode();

        if(!ResponseBodyCode.SUCCESS.hasSameValue(code)) {
            response.setStatusCode(HttpStatusCode.valueOf(code.getValue()));
        }
        return body;
    }
}
